<template>
    <input :id="id">
</template>
<script>
    import { mapGetters } from 'vuex'
    import _ from 'lodash'
    export default {
        name: 'DatePicker',
        props: ['value', 'id'],
        computed: {
            ...mapGetters({
                locale: 'locale'
            })
        },
        mounted () {
            this.destroyUnit().then(() => {
                this.initUnit()
            })
        },
        beforeDestroy () {
            this.destroyUnit()
        },
        methods: {
            initUnit () {
                const kendoDatePicker = $('#' + this.id).kendoDatePicker({
                    culture: this.locale,
                    dateInput: true,
                    format: 'yyyy/MM/dd',
                    value: _.isDate(this.value) ? this.value : null,
                    change: this.emitValue
                }).data('kendoDatePicker')

                kendoDatePicker.wrapper.css('width', '100%')
            },
            /**
             * 销毁控件实例
             */
            destroyUnit () {
                const unit = $('#' + this.id).data('kendoDatePicker')

                return new Promise((resolve) => {
                    if (!_.isEmpty(unit)) {
                        unit.destroy()
                    }
                    resolve()
                })
            },
            /**
             * 值冒泡到父级
             * @param e
             */
            emitValue (e) {
                const widget = e.sender
                this.$emit('input', widget.value())
            }
        }
    }
</script>